<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Sample as SampleModel;
use think\Db;

/**
 * 账单表模型
 */
class Audit extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_audit';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //获取该工程总的应收金额
    public static function getFinanceSumMoney($order_pid = 0){

        //应收金额
        $sum_price = 0;

        $where = ['order_pid'=>$order_pid];

        $list = Db::name('mill_order_archives')
            //->field('*,sum(a.weld) as weld_sum,sum(a.slot) as slot_sum,sum(a.torque) as torque_sum')
            ->field('order_id,color,thickness,model,sum(row_area) as row_area')
            ->where($where)
            ->group('order_id,color,thickness,model')
            ->select();

        $order_ids = Db::name('mill_order_archives')->where($where)->value("group_concat(order_id)");
        $order_ids = explode(',',$order_ids);

        //累加面积表计价
        foreach ($list as $v){
            //获取计价
            $price_where = [
                ['order_id','=',$v['order_id']],
                ['color','=',$v['color']],
                ['thickness','=',$v['thickness']],
                ['model','=',$v['model']],
            ];
            $price = Db::name('mill_order_archives_initial_price')
                ->where($price_where)
                ->value('price');
            $price = floatval($price);

            $sum_price += round(($v['row_area']*$price),3);
        }

        //累加（刨槽，焊缝，开孔）计价
        foreach ($order_ids as $order_id){
            //获取面积表信息
            $where = ['order_id'=>$order_id];

            $archives = Db::name('mill_order_archives')->field('sum(weld) as weld_sum,sum(slot) as slot_sum,sum(torque) as torque_sum')->where($where)->find();

            //获取焊缝计价
            $price = Db::name('mill_order_archives_initial_price')->where($where)->where(['type'=>1])->value('price');
            $price = floatval($price);
            //焊缝
            $sum_price += ($archives['weld_sum']*$price);

            //获取刨槽计价
            $price = Db::name('mill_order_archives_initial_price')->where($where)->where(['type'=>2])->value('price');
            $price = floatval($price);
            //刨槽
            $sum_price += ($archives['slot_sum']*$price);

            //获取开孔计价
            $price = Db::name('mill_order_archives_initial_price')->where($where)->where(['type'=>3])->value('price');
            $price = floatval($price);
            //开孔
            $sum_price += ($archives['torque_sum']*$price);

            //配件
            $extra_list = Db::name('mill_order_archives_extra')->where($where)->select();
            if(!empty($extra_list)){
                foreach ($extra_list as $extra){
                    //获取配件计价
                    $price = Db::name('mill_order_archives_initial_price')->where($where)->where(['model_sn'=>$extra['model_sn']])->value('price');
                    $price = floatval($price);
                    //配件
                    $sum_price += ($extra['number']*$price);
                }
            }

        }

        return $sum_price;
    }

    //获取对账单信息
    public static function fromData($id = 0){
        $info = Db::name('mill_audit')
            ->alias('a')
            ->field('a.*,o.engineering,c.company,c.create_time as order_time')
            ->leftJoin('mill_order o','o.order_sn=a.order_sn')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['a.id'=>$id])
            ->find();

        //获取总账单信息
        $finance = FinanceModel::financeInfo($info['order_pid']);
        //获取批次
        $batch = Db::name('mill_order')->where(['order_pid'=>$info['order_pid']])->column('batch','id');
        //获取同工程下已生产的对账单
        $info['before_audit'] = Db::name('mill_audit')
            ->field('rece_time,sum(rece_money) as rece_money,sum(row_area) as row_area')
            ->where([['order_pid','=',$info['order_pid']],['pid','=',0],['id','<',$id]])
            ->find();
        //已收款金额
        //$info['paid_money'] = $info['before_audit']['rece_money'];
        $info['receivable_money'] = $finance['receivable_money'];
        //已开票金额
        $info['invoice_money'] = $finance['invoice_money'];

        //合计应收金额
        $info['sum_money'] = 0;

        $new_list = [];//发货单列表
        $address_sn_span = [];//需要合并的发货单编号
        //遍历循环发货单
        $address_sns_arr = explode(',',$info['address_sns']);
        foreach ($address_sns_arr as $addsn){

            //遍历循环批次
            $list_where = [['g.address_sn','=',$addsn]];
            $order_ids = Db::name('mill_order_archives_give')->alias('g')->where($list_where)->column('DISTINCT order_id');
            foreach ($order_ids as $oid){

                //获取发货产品信息
                $list = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('a.color,a.thickness,a.model,sum(a.weld) as weld_sum,sum(a.slot) as slot_sum,sum(a.torque) as torque_sum,count(g.id) as give_sum,SUM(a.one_area) AS row_area,g.address_sn,g.address_time')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($list_where)
                    ->where(['g.order_id'=>$oid])
                    ->group('a.color,a.thickness,a.model')
                    ->order('a.order_id asc')
                    ->select();

                //循环获取各产品计价
                if(!empty($list)){

                    $weld = 0;//焊缝
                    $slot = 0;//刨槽
                    $torque = 0;//开孔
                    foreach ($list as &$v){

                        $price_where = [
                            ['order_id','=',$oid],
                            ['color','=',$v['color']],
                            ['thickness','=',$v['thickness']],
                            ['model','=',$v['model']],
                        ];
                        $price_info = Db::name('mill_order_archives_initial_price')->where($price_where)->find();
                        $price_info['row_area'] = $v['row_area'];
                        $v = array_merge($v,$price_info);

                        $v['unit'] = 'm²';
                        $v['batch'] = isset($batch[$v['order_id']])?$batch[$v['order_id']]:'';
                        //$v['row_area'] = ceil(($v['one_area'] * $v['give_sum'])*10000)/10000;

                        //合计应收金额
                        $info['sum_money'] += (ceil(($v['row_area']*$v['price'])*100)/100);

                        if(empty($address_sn_span[$addsn]))$address_sn_span[$addsn] = 1;
                        else $address_sn_span[$addsn] ++;

                        $weld += $v['weld_sum'];
                        $slot += $v['slot_sum'];
                        $torque += $v['torque_sum'];
                    }

                    //类型 1:焊缝 2: 刨槽 3:开孔
                    $tgd_type_arr = [
                        //合计焊缝
                        ['field'=>'weld','title'=>'焊缝长度','type'=>1,'value'=>$weld],
                        //合计开槽
                        ['field'=>'slot','title'=>'刨槽长度','type'=>2,'value'=>$slot],
                        //矩管长度
                        ['field'=>'torque','title'=>'开孔个数','type'=>3,'value'=>$torque],
                    ];
                    foreach ($tgd_type_arr as $tp){
                        if(!empty($tp['value'])){
                            $tp_info = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$oid,'type'=>$tp['type']])->find();
                            if($tp_info['price'] > 0){

                                $tp_info['unit'] = 'm';
                                $tp_info['give_sum'] = '';
                                $tp_info['row_area'] = $tp['value'];
                                $tp_info['model'] = $tp['title'];
                                $tp_info['basic_price'] = $tp_info['price'];

                                //合计应收金额
                                $info['sum_money'] += (ceil(($tp_info['row_area']*$tp_info['price'])*100)/100);

                                $list[] = array_merge($list[0],$tp_info);
                                $address_sn_span[$addsn] ++;
                            }
                        }
                    }

                    //配件
                    if(empty($info['before_audit']['rece_time'])){
                        $extra = Db::name('mill_order_archives_extra')
                            ->alias('e')
                            ->field('e.model_sn,e.number,p.*')
                            ->leftJoin('mill_order_archives_initial_price p','p.model_sn=e.model_sn')
                            ->where([['e.order_id','=',$oid],['p.price','>',0]])
                            ->select();
                        if(!empty($extra)){
                            foreach ($extra as $e){
                                $e_info = $list[0];
                                $e_info['unit'] = '';
                                $e_info['color'] = '';
                                $e_info['thickness'] = '';
                                $e_info['give_sum'] = $e['number'];
                                $e_info['row_area'] = '';
                                $e_info['model'] = $e['model_sn'];
                                $e_info['basic_price'] = $e_info['price'];

                                //合计应收金额
                                $info['sum_money'] += (ceil(($e_info['give_sum']*$e_info['price'])*100)/100);

                                $list[] = $e_info;
                                $address_sn_span[$addsn] ++;
                            }
                        }

                    }

                }
                $new_list = array_merge($new_list,$list);
            }

        }


        $info['list'] = $new_list;
        $info['address_sn_span'] = $address_sn_span;

        return $info;
    }

    // 表格制作
    //print 0:编辑模式 1:打印模式 2:导出模式
    public static function fromTabale($data = [],$print = 0){

        $table_head = [];
        $table_data[] = [
            "[11]<div style='text-align: left;font-weight: bold;' class='td-top td-50'>客户：{$data['company']}</div>",
            "[9]<div style='text-align: center;font-weight: bold;' class='td-top td-50'>合同约定铝锭价20000元/吨<br>每±500元/吨，2.5单价±4元/平方米</div>",
        ];
        $table_data[] = [
            "[11]<div style='text-align: left;font-weight: bold;' class='td-50'>工程名称：{$data['engineering']}（{$data['order_sn']}）</div>",
            "[9]<div style='text-align: center;font-weight: bold;' class='td-50'>加价（单位：元）</div>",
        ];

        //累积收款
        $rece_time = date('Y.m.d');
        if(!empty($data['before_audit']['rece_time']))$rece_time = date('Y.m.d',$data['before_audit']['rece_time']);
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>截止日{$rece_time}已对账金额及面积</div>",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$data['before_audit']['row_area']}</div>",
            "","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$data['before_audit']['rece_money']}</div>",
            "","","","","","","","","","",
        ];

        $table_data[] = [
            "发货日期",
            "批次",
            "计量单位",
            "面积",
            "数量(件)",
            "厚度(mm)",
            "板型",
            "颜色",
            "结算单价(元/m²)",
            "合价(元)",
            "发货单编号",
            "下单日期",
            "铝锭价",
            //"铝锭价约定日期",
            "浮动金额",
            "板型加价",
            "特殊颜色",
            "开料刀数",
            "基价",
            "结算价",
        ];

        //小计
        $area_sum = 0;
        $price_sum = 0;

        $address_sn_span = $data['address_sn_span'];
        foreach ($data['list'] as $k=>$v){

            $v_address_sn = '';
            if(!empty($address_sn_span[$v['address_sn']])){
                $v_address_sn = "[1:{$address_sn_span[$v['address_sn']]}]{$v['address_sn']}";
                unset($address_sn_span[$v['address_sn']]);
            }
            $v_num = empty($v['row_area'])?$v['give_sum']:$v['row_area'];
            $v_price = (ceil(($v_num*$v['price'])*100)/100);

            //小计
            $area_sum += floatval($v['row_area']);
            $price_sum += $v_price;

            $list_info = [
                date('Y.m.d',$v['address_time']),
                $v['batch'],
                $v['unit'],
                $v['row_area'],
                $v['give_sum'],
                $v['thickness'],
                $v['model'],
                $v['color'],
                $v['price'],
                $v_price,
                $v_address_sn,
                date('Y.m.d',$data['order_time']),
                $v['ingots_price'],
                //$v['ingots_time'],
                $v['float_price'],
                $v['plate_price'],
                $v['color_price'],
                $v['bend_price'],
                $v['basic_price'],
                $v['price'],
            ];
            if(empty($v_address_sn))unset($list_info[10]);
            $table_data[] = $list_info;
        }

        //小计
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>小计</div>",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$area_sum}</div>",
            "","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$price_sum}</div>",
            "","","","","","","","","","",
        ];
        //合计
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>合计</div>",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>".($area_sum+floatval($data['before_audit']['row_area']))."</div>",
            "","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>".($price_sum+floatval($data['before_audit']['rece_money']))."</div>",
            "","","","","","","","","","",
        ];
        //已付款金额
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>已付款金额(元)</div>",
            "","","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$data['receivable_money']}</div>",
            "","","","","","","","","","",
        ];
        //已开票金额
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>已开票金额(元)</div>",
            "","","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$data['invoice_money']}</div>",
            "","","","","","","","","","",
        ];
        /*//更新应收款金额和面积
        if($data['rece_money'] == 0){
            Db::name('mill_audit')->where(['id'=>$data['id']])->update(['rece_money'=>$price_sum,'row_area'=>$area_sum]);
            $data['rece_money'] = $price_sum;
            $data['row_area'] = $area_sum;
        }*/
        //应付金额
        $table_data[] = [
            "[3]<div style='text-align: center;font-weight: bold;' class='td-50'>应付金额(元)</div>",
            "","","","","","",
            "<div style='text-align: center;font-weight: bold;' class='td-50'>{$data['rece_money']}</div>",
            "","","","","","","","","","",
        ];
        //备注
        $table_data[] = [
            "[20]<div style='text-align: left;font-weight: bold;' class='td-50'>备注：请核对无误后及时安排付款，谢谢！</div>",
        ];
        //盖章
        $table_data[] = [
            "[10]<div style='text-align: left;font-weight: bold;' class='td-none td-top td-50'>甲方（盖章）： {$data['company']}</div>",
            "[10]<div style='text-align: left;font-weight: bold;' class='td-none td-top td-50'>乙方（盖章）： ".config('web_site_title')."</div>",
        ];
        //审核
        $table_data[] = [
            "[7]<div style='text-align: left;font-weight: bold;' class='td-none td-50'>核对人：</div>",
            "[6]<div style='text-align: left;font-weight: bold;' class='td-none td-50'>制单人：</div>",
            "[7]<div style='text-align: left;font-weight: bold;' class='td-none td-50'>复核人：</div>",
        ];
        //日期
        $table_data[] = [
            "[14]<div style='text-align: left;font-weight: bold;' class='td-none td-50'>日期：".date('Y年m月d日',$data['create_time'])."</div>",
            "[6]<div style='text-align: left;font-weight: bold;' class='td-none td-50'>日期：".date('Y年m月d日')."</div>",
        ];

        return ['head'=>$table_head,'data'=>$table_data];
    }

    // 打印模板
    //print 1:打印模式 2:导出模式
    public static function toHtml($data = [],$print = 1){

        //缩放比例
        $table_scaling = 1;

        //$html = '<html><style>th{font-size: 18px;font-weight: bold;}td{}</style><body style="margin: 4px;">';
        $html = '<html><style>th{font-size: 12px;font-weight: bold;}td{font-size: 12px;}</style><body style="margin: 4px;">';

        //头部
        /*$html .= '<table border="1" style="text-align: center;border-collapse: collapse;width: '.(21/$table_scaling).'cm;transform-origin: 0 0;"><thead>
                        <tr><th colspan="20" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';*/
        $html .= '<table border="1" style="text-align: center;border-collapse: collapse;transform-origin: 0 0;"><thead>
                        <tr><th colspan="20" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none td-bottom" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';
        $table_arr = self::fromTabale($data,1);
        foreach ($table_arr as $tk=>$tv){
            //头
            if($tk == 'head'){
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $html .= '
                            <th rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</th>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</thead>';
            }
            //体
            elseif($tk == 'data'){
                $html .= '<tbody>';
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $v['value'] = str_replace("\n","<br>",$v['value']);
                        $html .= '
                            <td rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</tbody>';
            }
        }
        $html .= '</table>';

        $js = 'window.print();';
        if($print == 2){
            $js = '$("table").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: "",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "对账单",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });';
        }
        //js
        $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script src="'.config('template.tpl_replace_string')['__STATIC__'].'/common/js/jquery.table2excel.js?v='.date('Ymd').'"></script>
                    <script type="text/javascript">
                        //去除边框
                        $(".td-none").parent().css("border-style","hidden")
                        //设置头部边框
                        $(".td-top").parent().css("border-top","1px solid black");
                        //设置底部边框
                        $(".td-bottom").parent().css("border-bottom","1px solid black");
                        //设置高度
                        $(".td-50").parent().css("height","50px");
                        //设置向下对齐
                        $(".text-bottom").parent().css("vertical-align","bottom");
                        //设置文字上下间距
                        $(".text-height").parent().css("line-height","28px");
                        //设置文字缩放比例
                        $("th,td").css("-webkit-transform","scale('.$table_scaling.')");
                        //设置文字缩放后左对齐
                        $(".scale-left").parent().css("transform-origin","0");
                        
                        '.$js.'
                    </script>';

        return $html;
    }

}
